<?php

namespace App\Admin\Actions\Department;

use App\Actions\DepartmentAction;
use App\Admin\Widgets\Form as WidgetsForm;
use App\Models\AdminUser;
use App\Models\Department;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Admin as AuthAdmin;

class AuditForm extends WidgetsForm implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $admin_user = AdminUser::find(AuthAdmin::user()->id);

        // 获取外部传递参数
        $id = $this->payload['id'] ?? null;

        $department = Department::query()->where('id', $id)->first();
        if (!$department) {
            return $this->response()->error('要审核的数据不存在');
        }

        if ($input['status'] == Department::STATUS_VERIFY_FAILED && (!isset($input['fail_reason']) || !$input['fail_reason'])) {
            return $this->response()->error('请填写拒绝理由');
        }
        try {
            DepartmentAction::make($department, $admin_user)->verify($input['status'], $input['fail_reason']);
            return $this->response()->success('操作成功')->refresh();
        } catch (\Throwable $th) {
            return $this->response()->error($th->getMessage());
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $id = $this->payload['id'] ?? null;
        $department = $id ? Department::find($id) : null;

        $form = $this;

        $this->width(7,3);
        if ($department) {
            $this->display('dwmc', '单位')->default($department->dwmc);
            $this->radio('status', '审核状态')->options(Department::$verifyStatusForm)->default(Department::STATUS_VERIFY_SUCCESS)->setLabelClass([ 'asterisk'])->required()
                ->when(Department::STATUS_VERIFY_FAILED, function () use ($form) {
                    $form->textarea('fail_reason','拒绝理由')->setLabelClass(['fail_reason-value', 'asterisk']);
                });
            $this->disableResetButton();
        }
    }
}
